package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

public class UserDao {
	private String sql;
	private String driver = "com.mysql.jdbc.Driver";
	private String url="jdbc:mysql://10.2.132.41:3306/family?useUnicode=true&characterEncoding=utf-8";
	private String user = "root";
	private String password = "sa";
	Connection con;
	Statement sta;
	ResultSet rs;

	public UserDao(String sql) {
		super();
		this.sql = sql;
	}
	
	//注册驱动，并获得连接
	public void getConnection(){
		try {
			Class.forName(driver);
			con=DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	//执行sql的查询，并返回结果
	public Map doSelect(){
		this.sql = sql;
		Map map = new HashMap();
		getConnection();
		try {
			sta = con.createStatement();
			rs = sta.executeQuery(sql);
			if(rs.next()){
				map.put("result", rs.getObject(1));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
			if(rs!=null){
				
					rs.close();
			}
			if(sta!=null){
				sta.close();
			}
			if(con!=null){
				con.close();
			}
			} catch (SQLException e) {
			  // TODO Auto-generated catch block
					e.printStackTrace();
			}
			
			
		}
		
		return map;
	}
	

}
